<template>
  <div class="app-container home">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="12" :lg="12" style="padding-left: 20px">
        <!-- 统计数据柱状图 -->
        <el-card style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <h3>存放每篇内容的统计数据</h3>
          </div>
          <div ref="chart" class="chart" style="width: 100%; height: 450px;"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12" :lg="12" style="padding-left: 20px">
        <!-- 用户留存率饼图 -->
        <el-card style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <h3>用户留存率</h3>
          </div>
          <div ref="pieChart" class="chart" style="width: 100%; height: 450px;"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="12" :lg="12" style="padding-left: 20px">
        <!-- 收益数据柱状图 -->
        <el-card style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <h3>用户收益统计</h3>
          </div>
          <div ref="revenueChart" class="chart" style="width: 100%; height: 450px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { listContent } from '@/api/system/content'
import { listStats } from '@/api/system/stats'
import { listRevenue } from '@/api/system/revenue'

export default {
  name: 'StatsChart',
  data() {
    return {
      chartInstance: null,
      pieChartInstance: null,
      revenueChartInstance: null,
      chartOptions: {
        tooltip: {},
        legend: {
          data: ['浏览量', '点赞数', '评论数']
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '浏览量',
            type: 'bar',
            data: []
          },
          {
            name: '点赞数',
            type: 'bar',
            data: []
          },
          {
            name: '评论数',
            type: 'bar',
            data: []
          }
        ]
      },
      pieChartOptions: {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '用户留存率',
            type: 'pie',
            radius: '50%',
            data: []
          }
        ]
      },
      revenueChartOptions: {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['广告收益', '打赏金额', '总收益', '总收益波动']
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '广告收益',
            type: 'bar',
            data: []
          },
          {
            name: '打赏金额',
            type: 'bar',
            data: []
          },
          {
            name: '总收益',
            type: 'bar',
            data: []
          },
          {
            name: '总收益波动',
            type: 'line',
            data: [],
            yAxisIndex: 0, // 使用同一个 y 轴
            smooth: true   // 使折线图平滑
          }
        ]
      }
    }
  },
  mounted() {
    this.initChart()
    this.fetchData()
    this.initPieChart()
    this.fetchPieData()
    this.initRevenueChart()
    this.fetchRevenueData()
  },
  methods: {
    // 初始化柱状图
    initChart() {
      this.chartInstance = echarts.init(this.$refs.chart)
      this.chartInstance.setOption(this.chartOptions)
    },
    fetchData() {
      listContent().then((response) => {
        if (response.code === 200) {
          const data = response.rows

          const contentIds = data.map((item) => `内容${item.contentId}`)
          const views = data.map((item) => item.views)
          const likes = data.map((item) => item.likes)
          const comments = data.map((item) => item.comments)

          this.chartOptions.xAxis.data = contentIds
          this.chartOptions.series[0].data = views
          this.chartOptions.series[1].data = likes
          this.chartOptions.series[2].data = comments

          this.chartInstance.setOption(this.chartOptions)
        } else {
          console.error('数据获取失败:', response.msg)
        }
      }).catch((error) => {
        console.error('请求失败:', error)
      })
    },
    // 初始化饼图
    initPieChart() {
      this.pieChartInstance = echarts.init(this.$refs.pieChart)
      this.pieChartInstance.setOption(this.pieChartOptions)
    },
    fetchPieData() {
      listStats().then((response) => {
        if (response.code === 200) {
          const data = response.rows

          const pieChartData = data.map((item) => ({
            value: item.retentionRate,
            name: `用户${item.userId}`
          }))

          this.pieChartOptions.series[0].data = pieChartData
          this.pieChartInstance.setOption(this.pieChartOptions)
        } else {
          console.error('数据获取失败:', response.msg)
        }
      }).catch((error) => {
        console.error('请求失败:', error)
      })
    },
    // 初始化收益柱状图
    initRevenueChart() {
      this.revenueChartInstance = echarts.init(this.$refs.revenueChart)
      this.revenueChartInstance.setOption(this.revenueChartOptions)
    },
    fetchRevenueData() {
      listRevenue().then((response) => {
        if (response.code === 200) {
          const data = response.rows

          const userIds = data.map(item => `用户${item.userId}`)
          const adRevenue = data.map(item => item.adRevenue)
          const revenueDonations = data.map(item => item.revenueDonations)
          const totalRevenue = data.map(item => item.totalRevenue)

          this.revenueChartOptions.xAxis.data = userIds
          this.revenueChartOptions.series[0].data = adRevenue
          this.revenueChartOptions.series[1].data = revenueDonations
          this.revenueChartOptions.series[2].data = totalRevenue
          this.revenueChartOptions.series[3].data = totalRevenue // 同时将总收益数据用于折线图

          this.revenueChartInstance.setOption(this.revenueChartOptions)
        } else {
          console.error('数据获取失败:', response.msg)
        }
      }).catch((error) => {
        console.error('请求失败:', error)
      })
    }

  }

}
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
